import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-131-分割回文串
 * @date 2025/5/10 23:10
 */
public class Solution131 {
    private boolean[][] f;
    private List<List<String>> ans = new ArrayList<>();
    private List<String> path = new ArrayList<>();
    private int n;

    public List<List<String>> partition(String s) {
        n = s.length();
        f = new boolean[n][n];
        for (boolean[] x : f) {
            Arrays.fill(x, true);
        }
        // 从左往右倒着动态规划实现O(1)判断回文串
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                f[i][j] = f[i + 1][j - 1] && (s.charAt(i) == s.charAt(j));
            }
        }
        dfs(s, 0);
        return ans;
    }

    private void dfs(String s, int i) {
        if (i == s.length()) {
            ans.add(new ArrayList<>(path));
            return;
        }
        // 以i当作左端点，j为右端点，分割原始字符串
        for (int j = i; j < n; j++) {
            if (f[i][j]) {
                path.add(s.substring(i, j + 1));
                dfs(s, j + 1); // 将分割后的字符串视为小字符串，继续分割
                path.remove(path.size() - 1); // 恢复现场
            }
        }
    }
}